

#import "RegistController.h"

@interface RegistController ()
@property (nonatomic) NSUInteger oriMaskCode;
@property (nonatomic, strong) NSMButton *submitBtn;
@end

@implementation RegistController
- (void)didInitialize {
    [super didInitialize];
    
    self.oriMaskCode = 0;
    self.usernameEditEnabled = YES;
    self.mobileEditEnabled = YES;
}

- (void)loadView {
    self.view = [UIScrollView new];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
}

- (void)initSubviews {
    [super initSubviews];
    
    self.view.backgroundColor = GROUP_TABLECOLOR;
    
    MyLinearLayout *layout = [MyLinearLayout linearLayoutWithOrientation:MyOrientation_Vert];
    layout.backgroundColor = GROUP_TABLECOLOR;
    layout.myHorzMargin = 0;
    layout.padding = UIEdgeInsetsMake(0, 0, 30, 0);
    [self.view addSubview:layout];
    layout.topBorderline = [[MyBorderline alloc] initWithColor:SEPARATOR_COLOR];
    
    MyLinearLayout *inputLayout = [MyLinearLayout linearLayoutWithOrientation:MyOrientation_Vert];
    inputLayout.backgroundColor = COLOR_4;
    inputLayout.myHorzMargin = 0;
    inputLayout.gravity = MyGravity_Horz_Fill;
    inputLayout.padding = UIEdgeInsetsMake(0, 15, 0, 15);
    [layout addSubview:inputLayout];
    
    NSArray <NSDictionary*> *items = [self itemsFromComponentOptions];
    @nsm_weak(self)
    for (int i=0; i<items.count; i++) {
        NSDictionary *item = items[i];
        NSString *key = item[@"id"];
        NSInteger tag = [item[@"tag"] integerValue];
        BOOL isRequired = [item[@"required"] boolValue];
        
        if (!isRequired) {
            // 非必填项目打上标记
            SetBit(self.maskCode, tag);
        }

        UITextField *field = [UITextField new];
        field.size = CGSizeMake(kScreenWidth-UIEdgeInsetsGetWidth(inputLayout.padding), 54);
        field.font = CustomFont(14);
        field.textColor = COLOR_0;
        field.tintColor = THEME_COLOR;
        field.placeholder = item[@"placeholder"];
        field.keyboardType = [item[@"keyboardType"] integerValue];
        field.secureTextEntry = [item[@"secure"] boolValue];
        field.clearButtonMode = UITextFieldViewModeWhileEditing;
        // [field setValue:COLOR_3 forKeyPath:@"_placeholderLabel.textColor"];
        [inputLayout addSubview:field];

        [field addBlockForControlEvents:UIControlEventEditingChanged block:^(UITextField *sender) {
            @nsm_strong(self)
            if (sender.text.length)
                SetBit(self.maskCode, tag);
            else
                ClearBit(self.maskCode, tag);
            self.mutableDic[key] = SafeString(sender.text);
            
            [self checkEnable];
        }];
        
        field.leftView = [self leftViewForTextField:item[@"icon"]];
        field.leftViewMode = UITextFieldViewModeAlways;
        
        // tag可以直接用来对比,此tag和i无关
        if (tag == 0) {
            field.enabled = self.usernameEditEnabled;
            field.text = _appCache.userInfo.userName;
            self.mutableDic[key] = SafeString(field.text);
            
            // 此处必有值,没有值代表有问题
            if (!self.usernameEditEnabled) {
                SetBit(self.maskCode, tag);
            }
        }
        else if (tag == 1) {
            field.enabled = self.mobileEditEnabled;
            field.text = _appCache.userInfo.mobile;
            self.mutableDic[key] = SafeString(field.text);
            
            // 此处必有值,没有值代表有问题
            if (!self.mobileEditEnabled) {
                SetBit(self.maskCode, tag);
            }
        }
        else if (tag == 2) {
            // 验证码
            NSMSMSButton *codeBtn = NSMSMSButton.new;
            codeBtn.size = CGSizeMake(87, 27);
            codeBtn.normalTitleColor = COLOR_4;
            codeBtn.disabledTitleColor = COLOR_3;
            codeBtn.normalBackgroundColor = THEME_COLOR;
            codeBtn.disabledBackgroundColor = DISABLED_COLOR;
            codeBtn.onActionHandler = ^(void (^completion)(BOOL)) {
                @nsm_strong(self)
                [self codeBtnAction:completion];
            };
            [codeBtn reloadAndUpdate];
            
            field.rightView = codeBtn;
            field.rightViewMode = UITextFieldViewModeAlways;
        }
        
        // 分割线
        if (i < items.count-1) {
            UIView *line = [UIView new];
            line.myHeight = kSinglePixel;
            line.backgroundColor = SEPARATOR_COLOR;
            [inputLayout addSubview:line];
        }
    }
    
    NSMButton *submitBtn = NSMButton.new;
    submitBtn.backgroundColor = THEME_COLOR;
    submitBtn.myTop = 48;
    submitBtn.myHorzMargin = 36;
    submitBtn.myHeight = 44;
    submitBtn.enabled = NO;
    submitBtn.titleLabel.font = BoldSystemFont(18);
    [submitBtn setTitleColor:COLOR_4 forState:UIControlStateNormal];
    [submitBtn addTarget:self action:@selector(onClickSubmit:) forControlEvents:UIControlEventTouchUpInside];
    submitBtn.title = self.apiType==ApiTypeRegist?@"注  册":@"提  交";
    [layout addSubview:submitBtn];
    ViewCorner(submitBtn, 6);
    _submitBtn = submitBtn;
    
    UIButton *protocol = [UIButton new];
    protocol.myTop = 15;
    protocol.myHorzMargin = 0;
    protocol.wrapContentHeight = YES;
    [protocol addTarget:self action:@selector(registerAgreement) forControlEvents:UIControlEventTouchUpInside];
    [layout addSubview:protocol];
    [protocol setAttributedTitle:AttributedString(@"注册代表你已同意",
                                                  CustomFont(14),
                                                  COLOR_1,
                                                  @"《用户服务协议》",
                                                  CustomFont(14),
                                                  THEME_COLOR,
                                                  NSTextAlignmentLeft,
                                                  0)
                        forState:UIControlStateNormal];
    protocol.myVisibility = self.apiType==ApiTypeRegist?MyVisibility_Visible:MyVisibility_Gone;
}

- (UIView *)leftViewForTextField:(NSString *)iconStr {
    UIButton *btn = [UIButton new];
    btn.size = CGSizeMake(28, 21);
    btn.tintColor = COLOR_1;
    btn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 7);
    [btn setImage:TemplateImage(iconStr) forState:UIControlStateNormal];
    return btn;
}

#pragma mark - method
- (void)setComponents:(NSArray<NSNumber *> *)components {
    _components = components;
    for (NSNumber *compent in components) {
        self.oriMaskCode = self.oriMaskCode | compent.integerValue;
    }
}

- (NSArray *)itemsFromComponentOptions {
    NSMutableArray<NSDictionary *> *items = @[].mutableCopy;
    for (NSNumber *compent in self.components) {
        NSInteger option = compent.integerValue;
        
        
        if (option & ComponentUsername) {
            // 用户名
            [items addObject:@{@"placeholder": InternationalString(@"用户名"),
                               @"keyboardType": @(UIKeyboardTypeAlphabet),
                               @"icon": @"regist_00",
                               @"id": @"username",
                               @"tag": @(0),
                               @"secure": @NO,
                               @"required": @YES}];
        }
        else if (option & ComponentMobile) {
            // 手机号
            [items addObject:@{@"placeholder": InternationalString(@"手机号"),
                               @"keyboardType": @(UIKeyboardTypeNumberPad),
                               @"icon": @"regist_01",
                               @"id": @"mobile",
                               @"tag": @(1),
                               @"secure": @NO,
                               @"required": @YES}];
        }
        else if (option & ComponentSMSCode) {
            // 短信验证码
            [items addObject:@{@"placeholder": InternationalString(@"验证码"),
                               @"keyboardType": @(UIKeyboardTypeNumberPad),
                               @"icon": @"regist_02",
                               @"id": @"code",
                               @"tag": @(2),
                               @"secure": @NO,
                               @"required": @YES}];
        }
        else if (option & ComponentPasswordOld) {
            // 旧密码
            [items addObject:@{@"placeholder": InternationalString(@"旧密码"),
                               @"keyboardType": @(UIKeyboardTypeAlphabet),
                               @"icon": @"regist_03",
                               @"id": @"oldpassword",
                               @"tag": @(3),
                               @"secure": @YES,
                               @"required": @YES}];
        }
        else if (option & ComponentPassword) {
            // 密码
            [items addObject:@{@"placeholder": InternationalString(@"密码(至少6位)"),
                               @"keyboardType": @(UIKeyboardTypeAlphabet),
                               @"icon": @"regist_03",
                               @"id": @"password",
                               @"tag": @(4),
                               @"secure": @YES,
                               @"required": @YES}];
        }
        else if (option & ComponentPasswordAgain) {
            // 密码确认
            [items addObject:@{@"placeholder": InternationalString(@"密码确认"),
                               @"keyboardType": @(UIKeyboardTypeAlphabet),
                               @"icon": @"regist_04",
                               @"id": @"again",
                               @"tag": @(5),
                               @"secure": @YES,
                               @"required": @YES}];
        }
        else if (option & ComponentNickname) {
            // 昵称
            [items addObject:@{@"placeholder": InternationalString(@"昵称"),
                               @"keyboardType": @(UIKeyboardTypeDefault),
                               @"icon": @"regist_00",
                               @"id": @"real_name",
                               @"tag": @(6),
                               @"secure": @NO,
                               @"required": @NO}];
        }
        else if (option & ComponentInvitationCode) {
            // 邀请码
            [items addObject:@{@"placeholder": InternationalString(@"邀请码"),
                               @"keyboardType": @(UIKeyboardTypeAlphabet),
                               @"icon": @"regist_06",
                               @"id": @"inviter",
                               @"tag": @(7),
                               @"secure": @NO,
                               @"required": @NO}];
        }
    }
    
    return items;
}

#pragma mark - setter/getter
- (void)setApiType:(ApiType)apiType {
    _apiType = apiType;
    
    self.mutableDic[@"type"] = FormatString(@"%@",@(apiType));
}

- (void)checkEnable {
    BOOL enable = (self.maskCode == self.oriMaskCode);
    _submitBtn.enabled = enable;
}

- (void)registerAgreement {
    @nsm_weak(self)
    [_appCache onceCacheForKey:kGlobalInfo success:^(id responseObject) {
        @nsm_strong(self)
        [self pushHTMLController:nil URLString:responseObject[@"protocol_url"] animated:YES];
    } failure:nil hud:YES];
}

#pragma mark - action
- (void)codeBtnAction:(void(^)(BOOL))completion {
    NSDictionary *param = @{@"mobile": SafeString(self.mutableDic[@"mobile"]),
                            @"type": IntegerString(self.apiType)};
    [_networker POST:@"publics/sendMsg" parameters:param success:^(id responseObject) {
        !completion?:completion(YES);
    } empty:^(NSMResponseObject *responseObject) {
        !completion?:completion(NO);
    } failure:^(NSError *error) {
        !completion?:completion(NO);
    } hud:NO];
}

- (void)onClickSubmit:(id)sender {
    [self.view endEditing:YES];
    
    NSString *urlStr = @"";
    switch (self.apiType) {
        case ApiTypeRegist:
            urlStr = @"publics/register";
            break;
        case ApiTypeForgot:
            urlStr = @"publics/changePwd";
            break;
        case ApiTypeModifyLogin:
            urlStr = @"mine/updatePassword";
            break;
        case ApiTypeModifyPay:
            urlStr = @"mine/updatePassword";
            break;
        case ApiTypeBindOnAccount:
        {
            urlStr = @"publics/bind_phone";
            [self.mutableDic addEntriesFromDictionary:self.constDic];
        }
            break;
        default:
            break;
    }
    self.mutableDic[@"type"] = IntegerString(_apiType);
    @nsm_weak(self)
    [_networker POST:urlStr parameters:self.mutableDic success:^(NSMResponseObject *responseObject) {
        @nsm_strong(self)
        if (self.apiType==ApiTypeForgot ||
            self.apiType==ApiTypeModifyLogin) {
            [self showAlert:SafeString(responseObject.desc) action:^(UIAlertAction *action) {
                [_noteCenter postNotificationOnMainThreadWithName:kUserPasswordDidChangeNotification object:nil];
            }];
        } else {
            [self showAlert:responseObject.desc action:^(UIAlertAction *action) {
                !self.didSumitSuccess?:self.didSumitSuccess(responseObject.data);
                [self.navigationController popViewControllerAnimated:YES];
            }];
        }
    } empty:nil failure:nil];
}

@end

